package com.interaction.qualitytimeaiagent.rag;

import com.interaction.qualitytimeaiagent.app.QualityTimeApp;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.markdown.MarkdownDocumentReader;
import org.springframework.ai.reader.markdown.config.MarkdownDocumentReaderConfig;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 亲子互动文档加载器
 */
@Component
//@Slf4j
public class QualitytimeDocumentLoader {

    private static final Logger logger = LoggerFactory.getLogger(QualityTimeApp.class);

    private final ResourcePatternResolver resolver ;
    public QualitytimeDocumentLoader(ResourcePatternResolver resolver) {
        this.resolver = resolver;
    }

    public List<Document> loadQualitytimeDocuments() {
        List<Document> allDoucument = new ArrayList<>();
        try {
            Resource[] resources = resolver.getResources("classpath:document/*.md");
            for (Resource resource : resources) {
                String filename = resource.getFilename();
                MarkdownDocumentReaderConfig config = MarkdownDocumentReaderConfig.builder()
                        .withHorizontalRuleCreateDocument(true)
                        .withIncludeCodeBlock(false)
                        .withIncludeBlockquote(false)
                        .withAdditionalMetadata("filename", filename)
                        .build();
                MarkdownDocumentReader markdownDocumentReader = new MarkdownDocumentReader(resource, config);
                allDoucument.addAll(markdownDocumentReader.get());
            }
        } catch (IOException e) {
            logger.error("文档加载失败",e);
        }

        return allDoucument;
    }
}
